#! /usr/bin/env python2  
# encoding=utf-8
import sys
reload(sys) 
sys.setdefaultencoding('utf8')
import os
ScriptPath = os.path.split( os.path.realpath( sys.argv[0] ) )[0]
import xmlrpclib
import ConfigParser
import datetime

# 使用单位更新电梯数量
# lift_count
config = ConfigParser.RawConfigParser()
config.read(ScriptPath+'/sys.cfg')
url = config.get('odoo','host')
uid = 1
pwd = config.get('odoo','password')
db = config.get('odoo','db')
models = xmlrpclib.ServerProxy('{}/xmlrpc/2/object'.format(url))

def group_by(model,field):
    countModel = models.execute_kw(db,uid,pwd,model,'read_group',[[]],{'fields':[field,'id'],'groupby':field})
    return countModel

def main():
    print u"开始更新使用单位电梯数量"
    # 方法2：用group_by
    use_companys = models.execute_kw(db,uid,pwd,'tyibs.base.lift.use.company','search_read',[[]],{'fields':['lift_count']})
    group_lifts = group_by('tyibs.base.lift','use_company_id')
    for company in use_companys:
        for lift in group_lifts:
            # 这里会有一种情况，没有使用单位的电梯被排成了一组
            if lift['use_company_id'] and company['id'] == lift['use_company_id'][0]:
                if company['lift_count'] != lift['use_company_id_count']:
                    print u"有更新使用单位"
                    models.execute_kw(db,uid,pwd,'tyibs.base.lift.use.company','write',[[company['id']],{'lift_count':lift['use_company_id_count']}])

    # 方法1：感觉效率太慢
    # use_company_ids = models.execute_kw(db,uid,pwd,'tyibs.base.lift.use.company','search_read',[[]],{'fields':['name','lift_count']})
    # for use_company in use_company_ids:
    #     lift_ids = models.execute_kw(db,uid,pwd,'tyibs.base.lift','search_read',[[['use_company_id','=',use_company['id']]]],{'fields':['id']})
    #     lift_count = len(lift_ids)
    #     if lift_count != use_company['lift_count']:
    #         models.execute_kw(db,uid,pwd,'tyibs.base.lift.use.company','write',[[use_company['id']],{'lift_count':lift_count}])
    #     else:
    #         pass

if __name__ == '__main__':
    main()